<template>
  <el-dialog
    v-model="visible"
    title="日常作业管理"
    width="800px"
    @open="loadDailyHomework"
  >
    <div class="daily-homework-manager">
      <!-- 添加日常作业 -->
      <div class="add-section">
        <el-button type="primary" @click="showAddDialog = true">
          添加日常作业
        </el-button>
      </div>

      <!-- 日常作业列表 -->
      <div class="homework-list">
        <el-table
          :data="dailyHomeworkList"
          row-key="id"
          border
          style="width: 100%"
        >
          <el-table-column prop="content" label="作业内容" min-width="200" />
          <el-table-column prop="isRequired" label="类型" width="100">
            <template #default="{ row }">
              <el-tag :type="row.isRequired ? 'danger' : 'info'">
                {{ row.isRequired ? '必须' : '非必须' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="isActive" label="状态" width="100">
            <template #default="{ row }">
              <el-switch
                v-model="row.isActive"
                @change="toggleStatus(row)"
              />
            </template>
          </el-table-column>
          <el-table-column label="操作" width="200">
            <template #default="{ row }">
              <el-button
                type="primary"
                size="small"
                @click="editHomework(row)"
              >
                编辑
              </el-button>
              <el-button
                type="danger"
                size="small"
                @click="deleteHomework(row)"
              >
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>

    <!-- 添加/编辑对话框 -->
    <el-dialog
      v-model="showAddDialog"
      :title="editingHomework ? '编辑日常作业' : '添加日常作业'"
      width="500px"
      append-to-body
    >
      <el-form
        ref="formRef"
        :model="formData"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="作业内容" prop="content">
          <el-input
            v-model="formData.content"
            type="textarea"
            :rows="3"
            placeholder="请输入作业内容"
          />
        </el-form-item>
        <el-form-item label="作业类型" prop="isRequired">
          <el-radio-group v-model="formData.isRequired">
            <el-radio :label="true">必须完成</el-radio>
            <el-radio :label="false">非必须完成</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showAddDialog = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit" :loading="loading">
            {{ editingHomework ? '更新' : '添加' }}
          </el-button>
        </span>
      </template>
    </el-dialog>

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="visible = false">关闭</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, reactive, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { dailyHomeworkApi } from '@/api/dailyHomework'

const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false
  }
})

const emit = defineEmits(['update:modelValue'])

const visible = computed({
  get: () => props.modelValue,
  set: (value) => emit('update:modelValue', value)
})

const dailyHomeworkList = ref([])
const showAddDialog = ref(false)
const editingHomework = ref(null)
const loading = ref(false)
const formRef = ref()

const formData = reactive({
  content: '',
  isRequired: true
})

const rules = {
  content: [
    { required: true, message: '请输入作业内容', trigger: 'blur' }
  ]
}

const loadDailyHomework = async () => {
  try {
    const response = await dailyHomeworkApi.getAll()
    dailyHomeworkList.value = response.data
  } catch (error) {
    console.error('加载日常作业失败:', error)
  }
}

const resetForm = () => {
  Object.assign(formData, {
    content: '',
    isRequired: true
  })
  editingHomework.value = null
  if (formRef.value) {
    formRef.value.resetFields()
  }
}

const editHomework = (homework) => {
  editingHomework.value = homework
  Object.assign(formData, {
    content: homework.content,
    isRequired: homework.isRequired
  })
  showAddDialog.value = true
}

const handleSubmit = async () => {
  if (!formRef.value) return

  try {
    await formRef.value.validate()
    loading.value = true

    if (editingHomework.value) {
      await dailyHomeworkApi.update(editingHomework.value.id, formData)
      ElMessage.success('日常作业更新成功')
    } else {
      await dailyHomeworkApi.create(formData)
      ElMessage.success('日常作业添加成功')
    }

    showAddDialog.value = false
    resetForm()
    loadDailyHomework()
  } catch (error) {
    console.error('操作失败:', error)
  } finally {
    loading.value = false
  }
}

const deleteHomework = async (homework) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除日常作业"${homework.content}"吗？`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    await dailyHomeworkApi.delete(homework.id)
    ElMessage.success('日常作业删除成功')
    loadDailyHomework()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
    }
  }
}

const toggleStatus = async (homework) => {
  try {
    await dailyHomeworkApi.toggle(homework.id, homework.isActive)
    ElMessage.success(homework.isActive ? '已启用' : '已禁用')
  } catch (error) {
    // 恢复原状态
    homework.isActive = !homework.isActive
    console.error('状态切换失败:', error)
  }
}
</script>

<style scoped>
.daily-homework-manager {
  padding: 20px 0;
}

.add-section {
  margin-bottom: 20px;
}

.homework-list {
  max-height: 400px;
  overflow-y: auto;
}
</style>